package logic

import (
	"api/model/mysql"
	"context"
	"goods_srv/cache"

	"goods_srv/goods"
	"goods_srv/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddCartLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAddCartLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddCartLogic {
	return &AddCartLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *AddCartLogic) AddCart(in *goods.AddCartRequest) (*goods.AddCartResponse, error) {

	g := mysql.NewGoods()
	err := g.GetDetail(int(in.GoodsId))
	if err != nil {
		logx.Error("商品信息查找失败")
		return nil, err
	}

	if g.ID == 0 {
		logx.Error("商品不存在")
		return nil, err
	}

	if g.GoodsNum < int(in.GoodsNum) {
		logx.Error("商品库存不足")
		return nil, err
	}

	goodsMap := map[string]interface{}{
		"goods_id":     in.GoodsId,
		"goods_name":   g.GoodsName,
		"goods_price":  g.GoodsPrice,
		"goods_num":    in.GoodsNum,
		"goods_status": 1,
	}

	err = cache.AddCart(int(in.UserId), int(in.GoodsId), goodsMap)
	if err != nil {
		logx.Error("商品信息保存失败:", err)
		return nil, err
	}

	return &goods.AddCartResponse{}, nil
}
